<template>
  <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图区域 -->
      <el-card class="box-card">
          <!-- 搜索组件 -->      
      <el-row :gutter="20">
          <el-col :span="7">
              <el-input placeholder="请输入内容" v-model="queryInfo.query" @clear="getUserList" clearable>
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
          </el-col>
          <el-col :span="4">
              <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </el-col>
      </el-row>

      <!-- 表单组件 -->
      <el-table
        :data="userlist"
        style="width: 100%">
        <el-table-column type="index" label="#"><!-- 索引列 -->
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <!-- Switch 开关 -->
              <el-switch
                  @change="userStateChange(scope.row)"
                  v-model="scope.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
              <!-- 按钮组件 -->
              <!-- {{scope.row.id}} -->
              <el-button type="primary" icon="el-icon-edit" circle size="small" @click="showEditDialog(scope.row.id)"></el-button>
              <!-- Tooltip 文字提示 -->
              <el-tooltip class="item" effect="light" content="Top Left 提示文字" placement="right-end" transition="el-fade-in-linear" :enterable="false">
                    <el-button type="info" icon="el-icon-setting" circle size="small"></el-button>
              </el-tooltip>
              <el-button type="danger" icon="el-icon-delete" circle size="small" @click="openDel(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部分页组件 -->
          <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryInfo.pagenum"
          :page-sizes="[1, 2, 3, 5]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next"
          :total="total">
        </el-pagination>
    </el-card>

    <!-- 添加用户弹框 Dialog 对话框-->
          <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            @close="addDialogClosed"
            >
            <!-- 对话框中的表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm('addFormRules')">确 定</el-button>
            </span>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog
          title="修改用户信息"
          :visible.sync="editDialogVisible"
          width="30%"
          @close="editDialogClose"
          :before-close="handleClose">
          <!-- 修改对话框的表单 -->
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    //自定义验证邮箱的规则
    var checkEmail = (rule, value, callback)=>{
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if(regEmail.test(value)) return callback() //合法
      callback(new Error('请输入合法的邮箱'))
    }
    //自定义验证手机号的规则
    var checkMobile =(rule, value, callback)=>{
      const regPhone = /^1[3|4|5|7|8][0-9]{9}$/
      if(regPhone.test(value)) return callback()
      callback(new Error('请输入合法的手机号'))
    }
    return {
      msg: '',
      // 获取用户列表的参数对象
      queryInfo:{   
        query: '',  //查询参数
        pagenum: 1, //当前页码
        pagesize: 2 //每页显示条数
      },
      userlist: [],
      total: 0,
      dialogVisible: false, //控制对话框的显示和隐藏
      editDialogVisible: false,//修改用户对话框
      //添加用户的表单对象
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      //添加用户的表单验证对象
      addFormRules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '用户名的长度在 3 到 5 个字符之间', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码不少于6个字符', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ],
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //编辑用户数据对象
      editForm:{
        email:''
      },
      //编辑验证对象
      editFormRules:{
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ],
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
      async getUserList(){
        const {data:res} = await this.$http.get('users',{params:this.queryInfo})
            // console.log(res)
            if(res.meta.status!==200) return this.$message.error('获取用户列表失败!')
            this.userlist = res.data.users
            this.total = res.data.total
      },
      //切换每页显示条数菜单触发
      handleSizeChange(newSize){
        // console.log(newSize)
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      //当前页改变时
      handleCurrentChange(newPage){
        console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      //监听switch用户状态开关的改变
      async userStateChange(userInfo){
        console.log(userInfo.mg_state)
        const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        //console.log(res)
        //判断用户状态是否改变
        if(res.meta.status!==200){
          this.$message.error('更新用户状态失败！')
          userInfo.mg_state =!userInfo.mg_state //保证用户状态没变
        } else{
          this.$message.success('更新状态成功!')
        }

      },
      //添加用户的提交
      submitForm(addFormRef){
        this.$refs.addFormRef.validate((valid) => {
          //console.log(valid)
          if (valid) {
            // alert('验证通过!');
            this.$http.post('users',this.addForm)
                .then((res)=>{
                  //console.log(res)
                  if(res.data.meta.status!==201) return this.$message.error(res.data.meta.msg)
                  this.$message.success(res.data.meta.msg)
                  //添加完，重新获取用户列表
                  this.getUserList()
                  //隐藏对话框
                  this.dialogVisible=false
                })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //监听对话框的@close事件 关闭对话框组件重置表单
      addDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },
      //监听修改对话框
      editDialogClose(){
        this.$refs.editFormRef.resetFields()
      },
      //显示编辑对话框
      async showEditDialog(id){
        //console.log(id)
        this.editDialogVisible = true
        const {data:res} = await this.$http.get(`users/${id}`)
        //console.log(res)
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.editForm = res.data
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //修改用户提交
      editUserInfo(){
         this.$refs.editFormRef.validate(async valid => {
           // console.log(valid)
           if (valid) {
              const {data:res} = await this.$http.put(`users/${this.editForm.id}`,{
                email: this.editForm.email,
                mobile: this.editForm.mobile
              })
                if(res.meta.status!==200) return this.$message.error('用户信息失败!')
                this.$message.success(res.meta.msg)
                this.editDialogVisible = false
                this.getUserList() //更新列表
           } else {
               this.$message.error('验证用户信息失败!')
               return false;
           }
         });
      },
      //删除
      openDel(id){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`users/${id}`)
          console.log(res)
          this.getUserList() //更新列表
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
  }
}
</script>

<style scoped>

</style>
